<?php
// +-----------------------------------------------------------------------------------------------
// | 简易CMS
// +-----------------------------------------------------------------------------------------------
// | [请手动修改文件描述]
// +-----------------------------------------------------------------------------------------------
// | Author: IT果农 <htmambo@163.com> <http://www.haolie.net>
// +-----------------------------------------------------------------------------------------------
// | Version $Id: AuthController.class.php 14 2016-09-24 06:11:25Z IT果农 <htmambo@163.com> $
// +-----------------------------------------------------------------------------------------------

namespace app\admin\controller;
use app\admin\model\AuthRule;
use app\admin\model\AuthGroup;

/**
 * 权限管理控制器
 * Class AuthController
 */
class Auth extends AdminController{

    /**
     * 后台节点配置的url作为规则存入auth_rule
     * 执行新节点的插入,已有节点的更新,无效规则的删除三项任务
     */
    public function updateRules(){

        //需要新增的节点必然位于$nodes
        $nodes    = $this->returnNodes(false);

        $AuthRule = model('AuthRule');
        $map      = array('module'=>'admin','type'=>array('in','1,2'));//status全部取出,以进行更新
        //需要更新和删除的节点必然位于$rules
        $rules    = $AuthRule->where($map)->order('name')->select();

        //构建insert数据
        $data     = array();//保存需要插入和更新的新节点
        foreach ($nodes as $value){
            $temp['name']   = $value['url'];
            $temp['title']  = $value['title'];
            $temp['module'] = 'admin';
            if($value['pid'] >0){
                $temp['type'] = AuthRule::RULE_URL;
            }else{
                $temp['type'] = AuthRule::RULE_MAIN;
            }
            $temp['status']   = 1;
            $data[strtolower($temp['name'].$temp['module'].$temp['type'])] = $temp;//去除重复项
        }

        $update = array();//保存需要更新的节点
        $ids    = array();//保存需要删除的节点的id
        foreach ($rules as $index=>$rule){
            $key = strtolower($rule['name'].$rule['module'].$rule['type']);
            if ( isset($data[$key]) ) {//如果数据库中的规则与配置的节点匹配,说明是需要更新的节点
                $data[$key]['id'] = $rule['id'];//为需要更新的节点补充id值
                $update[] = $data[$key];
                unset($data[$key]);
                unset($rules[$index]);
                unset($rule['condition']);
                $diff[$rule['id']]=$rule;
            }elseif($rule['status']==1){
                $ids[] = $rule['id'];
            }
        }
        if ( count($update) ) {
            foreach ($update as $k=>$row){
                if ( $row!=$diff[$row['id']] ) {
                    $AuthRule->where(array('id'=>$row['id']))->update($row);
                }
            }
        }
        if ( count($ids) ) {
            $AuthRule->where( array( 'id'=>array('IN',implode(',',$ids)) ) )->update(array('status'=>-1));
            //删除规则是否需要从每个用户组的访问授权表中移除该规则?
        }
        if( count($data) ){
            $AuthRule->insertAll(array_values($data));
        }
        if ( $AuthRule->getError() ) {
            trace('['.__METHOD__.']:'.$AuthRule->getError());
            return false;
        }else{
            return true;
        }
    }


    /**
     * 权限管理首页
     */
    public function index(){
        $this->pageTitle = '权限管理';
        return $this->fetch();
    }

    public function getDatas(){
        $list = $this->lists('AuthGroup',array('module'=>'admin'),'id asc');
        return $this->ajaxReturn($list);
    }
    public function groups(){
        $model = model('AuthGroup');
        $lists = $model->paginate(10);
        return $lists->render();

    }
    /**
     * 创建管理员用户组
     */
    public function createGroup(){
        if ( empty($this->auth_group) ) {
            $this->assign('auth_group',array('title'=>null,'id'=>null,'description'=>null,'rules'=>null,));//排除notice信息
        }
        $this->pageTitle = '新增用户组';
        return $this->fetch('editgroup');
    }

    /**
     * 编辑管理员用户组
     */
    public function editGroup(){
        $id = input('id', 0, 'intval');
        if(!$id) {
            $this->error('对不起，你没有指定要编辑的用户组！');
        }
        $auth_group = model('AuthGroup')
            ->where( array('module'=>'admin','type'=>AuthGroup::TYPE_ADMIN) )
            ->find($id);
        $this->assign('auth_group',$auth_group);
        $this->pageTitle = '编辑用户组';
        return $this->fetch();
    }


    /**
     * 访问授权页面
     */
    public function access(){
        $this->updateRules();
        $auth_group = model('AuthGroup')
            ->where( array('status'=>array('egt','0'),'module'=>'admin','type'=>AuthGroup::TYPE_ADMIN) )
            ->column('id,id,title,rules');
        $node_list   = $this->returnNodes();
        $map         = array('module'=>'admin','type'=>AuthRule::RULE_MAIN,'status'=>1);
        $main_rules  = model('AuthRule')->where($map)->column('name,id');
        $map         = array('module'=>'admin','type'=>AuthRule::RULE_URL,'status'=>1);
        $child_rules = model('AuthRule')->where($map)->column('name,id');

        $this->assign('main_rules', $main_rules);
        $this->assign('auth_rules', $child_rules);
        $this->assign('node_list',  $node_list);
        $this->assign('auth_group', $auth_group);
        $this->assign('this_group', $auth_group[input('group_id', 0, 'intval')]);
        //$this->pageTitle = '访问授权';
        return $this->fetch('managergroup');
    }

    /**
     * 管理员用户组数据写入/更新
     */
    public function writeGroup(){
        $data = input('post.');
        if(isset($data['rules'])){
            sort($data['rules']);
            $data['rules']  = implode( ',' , array_unique($data['rules']));
        }
        $data['module'] =  'admin';
        $data['type']   =  AuthGroup::TYPE_ADMIN;
        $AuthGroup       =  model('AuthGroup');
        if ( $data ) {
            if($data['id']) {
                $AuthGroup = $AuthGroup->isUpdate(true);
            }
            $r = $AuthGroup->save($data);
            if($r===false){
                $this->error('操作失败'.$AuthGroup->getError());
            } else{
                $this->success('操作成功!', url('index'));
            }
        }else{
            $this->error('操作失败'.$AuthGroup->getError());
        }
    }

    /**
     * 状态修改
     */
    public function changeStatus($method=null){
//        if ( empty($_REQUEST['id']) ) {
//            $this->error('请选择要操作的数据!');
//        }
        switch ( strtolower($method) ){
            case 'forbidgroup':
                $this->forbid('AuthGroup');
                break;
            case 'resumegroup':
                $this->resume('AuthGroup');
                break;
            case 'deletegroup':
                $this->delete('AuthGroup');
                break;
            default:
                $this->error($method.'参数非法');
        }
    }

    /**
     * 用户组授权用户列表
     */
    public function user($group_id){
        if(empty($group_id)){
            $this->error('参数错误');
        }

        $auth_group = model('AuthGroup')->where( array('status'=>array('egt','0'),'module'=>'admin','type'=>AuthGroup::TYPE_ADMIN) )
            ->column('id,id,title,rules');
        $prefix   = config('database.prefix');
        $l_table  = AuthGroup::MEMBER;
        $r_table  = $prefix.(AuthGroup::AUTH_GROUP_ACCESS);
        $model    = model('Member')->alias('m')
			->join($r_table.' a', 'm.uid=a.uid', 'LEFT' );
        $_REQUEST = array();
        $list = $this->lists($model,array('a.group_id'=>$group_id,'m.status'=>array('egt',0)),'m.uid asc','m.*');
        if(IS_AJAX) {
            $list = $list[config('AJAX_RETURN.root')];
        }
        int_to_string($list);
        $this->assign( '_list',     $list );
        $this->assign('auth_group', $auth_group);
        $this->assign('this_group', $auth_group[input('group_id', 0, 'intval')]);
        $this->pageTitle = '成员授权';
        return $this->fetch();
    }

    /**
     * 将分类添加到用户组的编辑页面
     */
    public function category(){
        $group_id = input('group_id');
        if(!$group_id) {
            return $this->error('请选择要操作的用户组！');
        }
        $this->assign('group_id', $group_id);
        $group_list     =   model('Categories')->lists();
        $authed_group   =   AuthGroup::getCategoryOfGroup($group_id);
        $this->assign('authed_group',   $authed_group);
        $this->assign('group_list',     $group_list);
        return $this->fetch();
    }

    public function tree($tree = null){
        $this->assign('tree', $tree);
        return $this->fetch('tree');
    }

    /**
     * 将用户添加到用户组的编辑页面
     */
    public function group(){
        $uid            =   I('uid');
        $auth_groups    =   model('AuthGroup')->getGroups();
        $user_groups    =   AuthGroup::getUserGroup($uid);
        $ids = array();
        foreach ($user_groups as $value){
            $ids[]      =   $value['group_id'];
        }
        $nickname       =   model('Member')->getNickName($uid);
        $this->assign('nickname',   $nickname);
        $this->assign('auth_groups',$auth_groups);
        $this->assign('user_groups',implode(',',$ids));
        $this->pageTitle = '用户组授权';
        return $this->fetch();
    }

    /**
     * 将用户添加到用户组,入参uid,group_id
     */
    public function addToGroup(){
        $uid = I('uid');
        $gid = I('group_id');
        if( empty($uid) ){
            $this->error('参数有误');
        }
        $AuthGroup = model('AuthGroup');
        if(is_numeric($uid)){
            if ( is_administrator($uid) ) {
                $this->error('该用户为超级管理员');
            }
            if( !model('Member')->where(array('uid'=>$uid))->find() ){
                $this->error('用户不存在');
            }
        }

        if( $gid && !$AuthGroup->checkGroupId($gid)){
            $this->error($AuthGroup->error);
        }
        if ( $AuthGroup->addToGroup($uid,$gid) ){
            $this->success('操作成功');
        }else{
            $this->error($AuthGroup->getError());
        }
    }

    /**
     * 将用户从用户组中移除  入参:uid,group_id
     */
    public function removeFromGroup(){
        $uid = I('uid');
        $gid = I('group_id');
        if( $uid==UID ){
            $this->error('不允许解除自身授权');
        }
        if( empty($uid) || empty($gid) ){
            $this->error('参数有误');
        }
        $AuthGroup = model('AuthGroup');
        if( !$AuthGroup->find($gid)){
            $this->error('用户组不存在');
        }
        if ( $AuthGroup->removeFromGroup($uid,$gid) ){
            $this->success('操作成功');
        }else{
            $this->error('操作失败');
        }
    }

    /**
     * 将分类添加到用户组  入参:cid,group_id
     */
    public function addToCategory(){
        $cid = I('cids');
        $gid = I('group_id');
        if( empty($gid) ){
            return $this->error('参数有误', '');
        }
        $AuthGroup = model('AuthGroup');
        if( !$AuthGroup->find($gid)){
            return $this->error('用户组不存在', '');
        }
        if( $cid && !$AuthGroup->checkCategoryId($cid)){
            return $this->error($AuthGroup->error, '');
        }
        if ( $AuthGroup->addToCategory($gid,$cid) ){
            return $this->success('操作成功', '');
        }else{
            return $this->error('操作失败', '');
        }
    }

    /**
     * 将模型添加到用户组  入参:mid,group_id
     */
    public function addToModel(){
        $mid = I('id');
        $gid = I('group_id');
        if( empty($gid) ){
            $this->error('参数有误');
        }
        $AuthGroup = model('AuthGroup');
        if( !$AuthGroup->find($gid)){
            $this->error('用户组不存在');
        }
        if( $mid && !$AuthGroup->checkModelId($mid)){
            $this->error($AuthGroup->error);
        }
        if ( $AuthGroup->addToModel($gid,$mid) ){
            $this->success('操作成功');
        }else{
            $this->error('操作失败');
        }
    }

}
